<template>
  <div class="page index-page">
    <div class="scroll-view">
      <customHeader middleTitle="同福商家调试页"
                    :gradual="true"
                    @rightCallBack="scan">
        <i class="zhk-sys"></i>
      </customHeader>
      <div class="page-body">
        <ul class="link-box"
            :class="{'no-split':!marketingcenterVisible&&!moganshanVisible}">
          <li @click="()=>{
              this.$router.push('/TransactionFlow');
            }">
            <div class="title">交易流水</div>
            <div class="desc">交易流水a</div>
            <i class="zhk-homepage_dzd"></i>
          </li>
          <li @click="linkToAccountStatement"
              v-if="true">
            <div class="title">对账单</div>
            <div class="desc">核对结算资金</div>
            <i class="zhk-homepage_dzd"></i>
          </li>
          <li @click="linkToBusinessAnalysis">
            <div class="title">经营分析</div>
            <div class="desc">商家数据分析</div>
            <i class="zhk-homepage_jyfx"></i>
          </li>
          <li @click="()=>{
              this.$router.push('/todoList');
            }">
            <div class="title">待办事项</div>
            <div class="desc">待办事项b</div>
            <i class="zhk-homepage_yxzx"></i>
          </li>
          <li @click="()=>{
              this.$router.push('/systemMsg');
            }">
            <div class="title">系统消息</div>
            <div class="desc">系统消息</div>
            <i class="zhk-homepage_yxzx"></i>
          </li>
          <li @click="()=>{
              this.$router.push('/selectMiniAppType/miniAppManage');
            }">
            <div class="title">小程序</div>
            <div class="desc">小程序</div>
            <i class="zhk-homepage_yyb"></i>
          </li>
           <li @click="()=>{
              this.$router.push('/memberManage');
            }">
            <div class="title">会员管理</div>
            <div class="desc">会员管理</div>
            <i class="zhk-homepage_yyb"></i>
          </li>
           <li @click="()=>{
              this.$router.push('/fxActivityRecord');
            }">
            <div class="title">返现营销</div>
            <div class="desc">返现营销</div>
            <i class="zhk-homepage_yyb"></i>
          </li>
           <li @click="()=>{
              this.$router.push('/messageMarketing');
            }">
            <div class="title">短信推广</div>
            <div class="desc">短信推广</div>
            <i class="zhk-homepage_yyb"></i>
          </li>
          <li @click="()=>{
              this.$router.push({path:'/splitBill'});
            }">
            <div class="title">分账</div>
            <div class="desc">分账</div>
            <i class="zhk-homepage_yyb"></i>
          </li>
          <li @click="()=>{
              this.$router.push({path:'/splitBill',query:{supplierId: '2099200505010628',status: 2}});
            }">
            <div class="title">分账</div>
            <div class="desc">分账</div>
            <i class="zhk-homepage_yyb"></i>
          </li>
           <li @click="()=>{
              this.$router.push({path:'/iframe',query:{title:'在线电子签约',url:'https://h5.leshuazf.com/wap/merBillAgreement/index.html?merchantId=5416019292&phone=15801206499&name=王华'}});
            }">
            <div class="title">乐刷签约2</div>
            <div class="desc">乐刷签约2</div>
            <i class="zhk-homepage_yyb"></i>
          </li>
           <li @click="()=>{
              this.$router.push('/mallList?mallTabIndex=0');
            }">
            <div class="title">大V推广套餐</div>
            <div class="desc">大V推广套餐</div>
            <i class="zhk-homepage_yyb"></i>
          </li>
           <li @click="()=>{
              this.$router.push('/memberStoredDataStatistics');
            }">
            <div class="title">会员储值</div>
            <div class="desc">会员储值</div>
            <i class="zhk-homepage_yyb"></i>
          </li>
          <li @click=linkToAlipay>
            <div class="title">小程序</div>
            <div class="desc">小程序</div>
            <i class="zhk-homepage_yyb"></i>
          </li>
          <li @click="()=>{this.$router.push('/concat');}">
            <div class="title">销售联系方式</div>
            <div class="desc">销售联系方式</div>
            <i class="zhk-homepage_yyb"></i>
          </li>
          <li @click="jumpTo('/jisuyun')">
            <div class="title">极速云</div>
            <div class="desc">极速云</div>
            <i class="zhk-homepage_yyb"></i>
          </li>
          <li @click="jumpTo('/selectMiniAppType')">
            <div class="title">选择大小号</div>
            <div class="desc">选择大小号</div>
            <i class="zhk-homepage_yyb"></i>
          </li>
         <li @click="jumpTo('/goodsManageIndex')">
            <div class="title">商品管理</div>
            <div class="desc">商品管理</div>
            <i class="zhk-homepage_yyb"></i>
          </li>
          <li @click="jumpTo('/storeManage')">
            <div class="title">门店管理</div>
            <div class="desc">门店管理</div>
            <i class="zhk-homepage_yyb"></i>
          </li>
          <li @click="jumpTo('/machinesManage')">
            <div class="title">机具管理</div>
            <div class="desc">机具管理</div>
          </li>
          <li @click="jumpTo('/feedback')">
            <div class="title">意见反馈</div>
            <div class="desc">意见反馈</div>
            <i class="zhk-homepage_yyb"></i>
          </li>
          <li @click="jumpTo('/activity/zfbConsumerCoupon')">
            <div class="title">支付宝城市消费券</div>
            <div class="desc">支付宝城市消费券</div>
            <i class="zhk-homepage_yyb"></i>
          </li>
          <li @click="jumpTo('/maSanInstructions')">
            <div class="title">设备使用说明</div>
            <div class="desc">设备使用说明</div>
            <i class="zhk-homepage_yyb"></i>
          </li>
          <li @click="jumpTo('/couponMarketing')">
            <div class="title">券营销</div>
            <div class="desc">券营销</div>
             <i class="zhk-homepage_yyb"></i>
          </li>
          <li @click="jumpTo('/ethApp')">
            <div class="title">E团火收银软件</div>
            <div class="desc">E团火收银软件</div>
             <i class="zhk-homepage_yyb"></i>
          </li>
        </ul>
        <div class="mall-enter"
             @click="linkToMall"
             v-if="true">
          <div class="title">设备商城</div>
          <p class="content">各种便捷的收款神器</p>
          <div class="link-to">去订购</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import config from "../../base/profile/config.json";
import customHeader from "../../components/header/header";
import { Toast, MessageBox, Loadmore } from "mint-ui";
import jsBridge from "../../tools/jsBridge.js";
import CountUp from "countup.js";
import echarts from "echarts";
export default {
  name: "index",
  data() {
    return {
      isChartLoad: false,
      backClickTime: 0,
      backClickTimeId: "",
      urlParams: "",
      todayDataUpdateTime: null,
      trendReportChart: null,
      isHaveShop: true,
      //showManageanalyze: false,
      indexPageCountSprice: "",
      marketingcenterVisible: false, //营销中心显示
      diagnoseVisible: false, //经营诊断显示
      moganshanVisible: false, //莫干山显示
    };
  },
  methods: {
    linkToAlipay() {
      AppUtil.call(AppUtil.APIS.OPEN_APP, { url: "alipays://platformapi/startapp?appId=20000067&url=alipays://platformapi/startapp?appId=2019041063856279&page=pages/index/main" }, function (result) {
        if (result.success == 'false') {
          Toast('检测到您尚未安装支付宝，请安装支付宝');
        }
      });
    },
    getUrlParam: function(url, name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      var hash = url.split("?");
      if (hash.length > 1) {
        var r = url.split("?")[1].match(reg);
        if (r != null) {
          return decodeURI(r[2]);
        }
      }
      return null;
    },
    //扫码绑定
    scan() {
      if (this.scanClick) {
        return;
      }
      this.scanClick = true;
      setTimeout(() => {
        this.scanClick = false;
      }, 2000);
      const _this = this;
      if (!this.isHaveShop) {
        this.confirmShop();
      } else {
        try {
          AppUtil.call(AppUtil.APIS.SCAN, {}, (response)=> {
            if (
              response &&
              (response.success === true || response.success === "true")
            ) {
              const url = response.resultObject;
              this.scanRequest(url);

            } else if (response && response.code && response.code == "-10") {
              //未扫码，返回，不处理
            } else {
              Toast("扫码失败");
            }
          });
        } catch (err) {

        }
      }
    },
    scanRequest(scanResult) {
      const url = `newapp/voice/scanQr.do?scanResult=${encodeURIComponent(
        scanResult
      )}`;
      this.ajax({
        url: url,
        type: "get",
        controlLoading: true
      })
        .then(result => {
          this.title = "识别结果";
          if (result.success) {
            const res = result.resultObject;

            if (res.action == 1) {
              //码卡龙配网
              this.$router.push({
                path: "/qrCodeSound/mainSettings/networkSetting",
                query: { sn: res.sn, close: "true" }
              });
            } else if (res.action == 2) {
              //绑定门店
              sessionStorageClient.putJSON("deviceStoreList", res.shopLists); //将门店列表存储，绑定门店页面使用
              this.$router.push({
                path: "/qrCodeSound/bindingStore",
                query: {
                  sn: res.sn,
                  type: res.type,
                  close: "true"
                }
              });
            } else if (res.action == 3) {
              //开通进件
              this.$router.push({
                path: "/qrCodeSound/authNone",
                query: {
                  className: "mkl-unopen",
                  shopId: res.shopId,
                  sn: res.sn,
                  type: res.type,
                  close: "true"
                }
              });
            } else if (res.action == 4) {
              //主设置面板
              const data = res["data"];
              this.$router.push({
                path: "/qrCodeSound/mainSettings",
                query: {
                  sn: data.sn,
                  type: data.type,
                  shopId: data.shopId,
                  close: "true"
                }
              });
            } else if (res.action == 5) {
              //扫进件二维码（状态为进件中 跳转到门店管理页面）
              this.$router.push({
                path: "/storeManage"
              });
            }
          } else if (result.code == -2) {
            //没有权限
            MessageBox({
              title: "",
              message: "没有权限",
              showCancelButton: false,
              confirmButtonText: "知道了",
              closeOnClickModal: false
            }).then(action => {
              if (action == "confirm") {
                jsBridge.closeWindow();
              }
            });
          } else {
            MessageBox({
              title: "",
              message: result.msg,
              showCancelButton: false,
              confirmButtonText: "知道了",
              closeOnClickModal: false
            }).then(action => {
              if (action == "confirm") {
                jsBridge.closeWindow();
              }
            });
          }
        })
        .catch(err => {
          this.title = "识别结果";
          MessageBox({
            title: "",
            message: "扫码服务错误",
            showCancelButton: false,
            confirmButtonText: "知道了",
            closeOnClickModal: false
          }).then(action => {
            if (action == "confirm") {
              jsBridge.closeWindow();
            }
          });
        });
    },
    scanCallback(sn, bzCode) {
      const url = `app/voice/scanBindQr.do?sn=${sn}&o=${bzCode}`;
      this.ajax({
        url: url,
        type: "get",
        controlLoading: true
      })
        .then(res => {
          if (res.success) {
            if (bzCode == "2") {
              //码卡龙配网
              this.$router.push({
                path: "/qrCodeSound/mainSettings/networkSetting",
                query: { sn: sn }
              });
              return;
            }
            if (res.resultObject.binded) {
              if (
                res.resultObject.openPayStatus === 0 &&
                res.resultObject.type == "18"
              ) {
                this.$router.push({
                  path: "/qrCodeSound/authNone",
                  query: {
                    className: "mkl-unopen",
                    shopId: res.resultObject.shopId,
                    sn: res.resultObject.sn,
                    type: res.resultObject.type
                  }
                });
              } else {
                this.$router.push({
                  path: "/qrCodeSound/mainSettings",
                  query: {
                    sn: res.resultObject.sn,
                    type: res.resultObject.type,
                    shopId: res.resultObject.shopId
                  }
                });
              }
            } else {
              //没有绑定
              if (res.code == 301) {
                //扫底部码时，设备未绑定门店
                this.$router.push({
                  path: "/qrCodeSound/authNone",
                  query: { className: "mkl-unbind" }
                });
              } else {
                sessionStorageClient.putJSON(
                  "deviceStoreList",
                  res.resultObject.shopLists
                ); //将门店列表存储，绑定门店页面使用
                this.$router.push({
                  path: "/qrCodeSound/bindingStore",
                  query: {
                    sn: res.resultObject.sn,
                    type: res.resultObject.type
                  }
                });
              }
            }
          } else if (res.code == -2) {
            //没有权限
            MessageBox({
              title: "",
              message: "没有权限",
              showCancelButton: false,
              confirmButtonText: "知道了"
            });
            //  this.$router.push({path:"/qrCodeSound/authNone",query:{className:"auth-none",type:res.resultObject.type}});
          } else {
            MessageBox({
              title: "",
              message: res.msg,
              showCancelButton: false,
              confirmButtonText: "知道了"
            });
          }
        })
        .catch(err => {

        });
    },
    //跳转商城
    linkToMall() {
      //防止下拉刷新时候触发跳转
      if (this.topStatus == "drop" || this.topStatus == "loading") {
        return;
      }
      if (!this.isHaveShop) {
        this.confirmShop();
      } else {
        this.$router.push({ path: "/mallList" });
      }
    },
    //跳转对账单
    linkToAccountStatement() {
      //防止下拉刷新时候触发跳转
      if (this.topStatus == "drop" || this.topStatus == "loading") {
        return;
      }
      if (!this.isHaveShop) {
        this.confirmShop();
      } else {
        this.$router.push("/accountStatement");
      }
    },

    //跳转经营分析
    linkToBusinessAnalysis() {
      //防止下拉刷新时候触发跳转
      if (this.topStatus == "drop" || this.topStatus == "loading") {
        return;
      }
      if (!this.isHaveShop) {
        this.confirmShop();
      } else {
        this.$router.push("/businessAnalysis");
      }
    },
    jumpTo(path){
      this.$router.push(path);
    },
    //是否有门店
    confirmShop(succFun) {
      let userId = "";
      MessageBox({
        title: "",
        message: "暂无门店",
        cancelButtonClass: "cancelBlue",
        showCancelButton: true,
        confirmButtonText: "获取口碑门店",
        cancelButtonText: "新增门店"
      }).then(action => {
        if (action === "confirm") {
          AppUtil.call(AppUtil.APIS.OPEN_AUTHV2, {}, function(result) {
            if (
              result != null &&
              result.success &&
              result.resultObject != null
            ) {
              userId = result.resultObject;
            }
          });
          this.confirmAliOauthResult(userId, succFun);
        } else {
          this.$router.push("/storeManage/editStore");
        }
      });
    },
    //确认是否授权
    confirmAliOauthResult(userId, succFun) {
      MessageBox({
        title: "",
        message: "是否授权成功?",
        showCancelButton: true,
        confirmButtonText: "授权成功",
        cancelButtonText: "取消"
      }).then(action => {
        if (action === "confirm") {
          if (userId != "") {
            this.indexAliOauthCallBack(userId, succFun);
          } else {
            Toast("授权失败！");
          }
        }
      });
    },
    indexAliOauthCallBack(aliId, succFun) {
      if (aliId == null || aliId == undefined) {
        return false;
      }
      const serverUrl = "/merchantApp/index/queryKbShop.do?aliId=" + aliId;

      this.ajax({
        url: serverUrl,
        type: "get",
        controlLoading: true
      })
        .then(result => {
          if (String(result.success) == "true") {
            if (succFun) {
              succFun();
            } else {
              this.initUser();
            }
          } else {
            if (result.code == "-1") {
              Toast("拉取失败，未订购过纵横客相关产品或未创建口碑门店!");
            } else if (result.code == "-2") {
              Toast("已绑定口碑商户!");
            } else if (result.code == "-3") {
              Toast("关联失败，该商户已与" + result.msg + "关联");
            } else if (result.code == "-4") {
              Toast("此商户未订购纵横客的服务!");
            }
          }
        })
        .catch(err => {

        });
    },
    getSplitNumberCompany(string) {
      var str = string;
      var arr = new Array();
      var i = 0;
      while (i < str.length) {
        var s = "";
        while (str.charCodeAt(i) < 256) {
          s = s + str.charAt(i);
          i++;
        }
        arr.push(s);
        var s = "";
        while (str.charCodeAt(i) > 256) {
          s = s + str.charAt(i);
          i++;
        }
        arr.push(s);
      }

      return arr;
    },
    getTrendConfig() {
      return {
        yAxisNames: { todayPayAmt: "单位:元" },
        legendData: {
          todayPayAmt: ["实收金额"]
        },
        seriesNames: {
          todayPayAmt: ["实收金额"]
        },
        option: {
          title: {
            x: "center"
          },
          tooltip: {
            trigger: "axis",
            formatter: function(param) {
              if (param.length == 1) {
                if (typeof param[0].value == "undefined") {
                  return (
                    "时间:" +
                    param[0].name +
                    "<br>" +
                    param[0].seriesName +
                    ":0"
                  );
                } else {
                  return (
                    "时间:" +
                    param[0].name +
                    "<br>" +
                    param[0].seriesName +
                    ":" +
                    param[0].value
                  );
                }
              } else if (param.length == 2) {
                if (
                  typeof param[0].value == "undefined" &&
                  typeof param[1].value == "undefined"
                ) {
                  return (
                    "时间:" +
                    param[0].name +
                    "<br>" +
                    param[0].seriesName +
                    ":0" +
                    "<br>" +
                    param[1].seriesName +
                    ":0"
                  );
                } else {
                  return (
                    "时间:" +
                    param[0].name +
                    "<br>" +
                    param[0].seriesName +
                    ":" +
                    param[0].value +
                    "<br>" +
                    param[1].seriesName +
                    ":" +
                    param[1].value
                  );
                }
              }
            }
          },
          grid: {
            width: "90%",
            left: "3%",
            right: "4%",
            bottom: "2%",
            containLabel: true
          },
          calculable: true,
          legend: {
            orient: "horizontal",
            data: [],
            selectedMode: "single"
          },
          xAxis: [
            {
              type: "category",
              name: "",
              boundaryGap: false,
              data: [],
              splitLine: {
                boundaryGap: false,
                lineStyle: {
                  color: "#dbdbdb"
                }
              },
              axisLine: {
                lineStyle: {
                  color: "#a7a7a7"
                }
              },
              axisTick: {
                lineStyle: {
                  color: "#a7a7a7"
                }
              },
              axisLabel: {
                textStyle: {
                  color: "#a7a7a7"
                }
              }
            }
          ],
          yAxis: [
            {
              type: "value",
              scale: true,
              //                     splitNumber:5,
              name: "",
              splitLine: {
                boundaryGap: false,
                lineStyle: {
                  color: "#dbdbdb"
                }
              },
              axisLine: {
                lineStyle: {
                  color: "#a7a7a7"
                }
              },
              axisTick: {
                lineStyle: {
                  color: "#a7a7a7"
                }
              },
              axisLabel: {
                formatter: function(v) {
                  return v;
                },
                textStyle: {
                  color: "#a7a7a7"
                }
              }
            }
          ],
          calculable: true,
          series: [
            {
              name: "会员总数",
              type: "line",
              data: [],
              //stack:"总量",
              areaStyle: { normal: {} }
            },
            {
              name: "新增会员数",
              type: "line",
              data: [],
              //stack:"总量",
              areaStyle: { normal: {} }
            }
          ],
          color: ["#2eb6f5", "#ff6600"]
        }
      };
    },

    parseDiagnostTitle(diagnoseItem) {
      for (var rule in this.configInfo.diagnoseTitle) {
        var el = rule.replace(/rate/g, diagnoseItem.industryRate);
        if (eval(el)) {
          return this.configInfo.diagnoseTitle[rule][diagnoseItem.diagnoseCode];
        }
      }
    },
    adaptDiagnoseData(result) {
      var warningContent = [];
      var recommendedActs = [];
      var self = this;
      var totalStartActCnt = 0;
      if (result.diagnosisList && result.diagnosisList.length > 0) {
        for (var i = 0; i < result.diagnosisList.length; i++) {
          var diagnosisItem = result.diagnosisList[i];
          var act = { diagnoseCode: diagnosisItem.diagnoseCode };
          totalStartActCnt += parseInt(diagnosisItem.hasStartActCnt);

          //存在进行中的活动就不允许继续创建
          if (parseInt(diagnosisItem.hasStartActCnt) > 0) {
            continue;
          }

          act.diagnoseTitle = self.parseDiagnostTitle(diagnosisItem);
          if (diagnosisItem.diagnoseCode == 1) {
            //会员流失率高
            diagnosisItem.activityType = "43";
            act.activityType = "43";
            act.actTypeName = "挽回流失会员";
            act.imgSrc = "../static/images/index_ls.png";
          } else if (diagnosisItem.diagnoseCode == 2) {
            //会员数量过少
            diagnosisItem.activityType = "46";
            act.activityType = "46";
            act.actTypeName = "新会员招募";
            act.imgSrc = "../static/images/index_xhy.png";
          } else if (diagnosisItem.diagnoseCode == 3) {
            //回头客较少
            if (diagnosisItem.configCode.indexOf("COMPOSED_ACTIVITY") != -1) {
              diagnosisItem.activityType = "51";
              act.activityType = "51";
              act.actTypeName = "消费送券";
              act.imgSrc = "../static/images/index_xfs.png";
            } else {
              diagnosisItem.activityType = "22";
              act.activityType = "22";
              act.actTypeName = "消费送券";
              act.imgSrc = "../static/images/index_xfs.png";
            }
          }

          if (diagnosisItem.voucherMinConsume.split("|").length > 0) {
            diagnosisItem.promoTools = new Array();
            var voucherMinConsumes = diagnosisItem.voucherMinConsume.split("|");
            var promoSendRuleMincosts = diagnosisItem.promoSendRuleMincost.split(
              "|"
            );
            var voucherWorthValues = diagnosisItem.voucherWorthValue.split("|");
            var voucherRelativeTimes = diagnosisItem.voucherRelativeTime.split(
              "|"
            );
            var voucherTypes = diagnosisItem.voucherType.split("|");
            var activityValidDayss = diagnosisItem.activityValidDays.split("|");
            var configCodes = diagnosisItem.configCode.split("|");
            var consumeCodes = diagnosisItem.consumeCode.split("|");
            var crowdDescs = diagnosisItem.crowdDesc.split("|");
            var crowdGroups = diagnosisItem.crowdGroup.split("|");
            var crowdGroupIds = diagnosisItem.crowdGroupId.split("|");
            var crowdNames = diagnosisItem.crowdName.split("|");

            for (var j = 0; j < voucherMinConsumes.length; j++) {
              var promTool = {};
              promTool.voucherMinConsume = voucherMinConsumes[j];
              promTool.promoSendRuleMincost = promoSendRuleMincosts[j];
              promTool.voucherWorthValue = voucherWorthValues[j];
              promTool.voucherRelativeTime =
                voucherRelativeTimes.length > 2
                  ? voucherRelativeTimes[j]
                  : voucherRelativeTimes[0];
              promTool.activityValidDayss =
                activityValidDayss.length > 2
                  ? activityValidDayss[j]
                  : activityValidDayss[0];
              promTool.configCode =
                configCodes.length > 2 ? configCodes[j] : configCodes[0];
              promTool.consumeCode =
                consumeCodes.length > 2 ? consumeCodes[j] : consumeCodes[0];
              promTool.crowdDesc =
                crowdDescs.length > 2 ? crowdDescs[j] : crowdDescs[0];
              promTool.crowdGroup =
                crowdGroups.length > 2 ? crowdGroups[j] : crowdGroups[0];
              promTool.crowdGroupId =
                crowdGroupIds.length > 2 ? crowdGroupIds[j] : crowdGroupIds[0];
              promTool.crowdName =
                crowdNames.length > 2 ? crowdNames[j] : crowdNames[0];
              promTool.voucherType =
                voucherTypes.length > 2 ? voucherTypes[j] : voucherTypes[0];

              diagnosisItem.promoTools.push(promTool);
            }
          }

          diagnosisItem.createPageUrl =
            self.configInfo.createActPageUrl[diagnosisItem.activityType];
          act.order = self.configInfo.diagnoseOrder[diagnosisItem.diagnoseCode];

          recommendedActs.push(act);
        }
      }

      recommendedActs.sort(function(act1, act2) {
        return act1.order - act2.order;
      });

      for (var i = 0; i < recommendedActs.length; i++) {
        warningContent.push(recommendedActs[i].diagnoseTitle);
      }

      if (result.intelMarketingRecom) {
        if (result.intelMarketingRecom.geneOnPos) {
          warningContent.push("小票营销未开启");
          recommendedActs.push({
            activityType: "25",
            actTypeName: "扫码送券",
            imgSrc: "../static/images/index_sm.png"
          });
        }
      }

      var hasDone =
        result.optimizedItem.totalOptimizedItemCnt ==
        result.optimizedItem.acceptedOptimizedItemCnt;
      return {
        totalStartActCnt: totalStartActCnt,
        warningContent: warningContent.join("，"),
        recommendedActs: recommendedActs,
        hasDone: hasDone
      };
    },
    //初始化用户信息
    initUser() {
      this.ajax({
        url: "/newapp/merchantApp/index/queryUserData.do",
        type: "get",
        controlLoading: true
      })
        .then(result => {
          if (String(result.success) == "true") {
            sessionStorageClient.putJSON("user", result.resultObject);
            let authMinusData = {};
            authMinusData = this.getOAuthMinus(
              authMinusData,
              result.resultObject.authMinus
            );
            this.isHaveShop =
              result.resultObject.isHaveShop == false
                ? result.resultObject.isHaveShop
                : true;
          }
        })
        .catch(err => {

        });
    },

    //首页权限
    getOAuthMinus(result, authMinus) {
      var minusHtml = [];
      var indexCode = [];
      if (authMinus != null && authMinus.length > 0) {
        for (var i = 0; i < authMinus.length; i++) {
          var minus = authMinus[i];
          minusHtml.push(this.configInfo.minus[minus.taskCode]);
          if (minus.taskCode == "app.home") {
            //首页权限项
            indexCode = this.getMinuCode(minus.children, indexCode);
          }
        }
        result.minusHtml = minusHtml;
      }
      result.indexCode = indexCode;
      return result;
    },

    getUserServiceInfo: function(callBack) {
      //先读缓存
      var userServiceInfo = sessionStorage.getItem("userServiceInfo");
      if (userServiceInfo) {
        this.queryDiagnoseData(JSON.parse(userServiceInfo).data);
        return;
      }

      let future = { id: Date.now(), finish: false, data: "", success: "" };
      this.ajax({
        url: "/merchantApp/index/queryUserServiceInfo.do",
        type: "get",
        controlLoading: true
      })
        .then(result => {
          future.finish = true;
          future.success = result.success;
          future.data = result.resultObject;

          //如果后端返回成功才写缓存
          if (result.success) {
            sessionStorage.setItem("userServiceInfo", JSON.stringify(future));

            this.queryDiagnoseData(future.data);
          } else {
            future.finish = true;
            future.success = false;
            future.data = {};
          }
        })
        .catch(err => {
          future.finish = true;
          future.success = false;
          future.data = {};
        });
    },


    gotoOAuthCode() {
      //请求bmserver获取授权码
      const serverUrl = "/app/oauth/getOAuthCode.do";

      this.ajax({
        url: serverUrl,
        type: "get",
        controlLoading: true
      })
        .then(result => {
          if (String(result.success) == "true") {
            var resultObject = result.resultObject;
            //跳转到crossairw服务，进行授权验证
            var oauthUrl = config.oauthUrl + resultObject;

            AppUtil.call(AppUtil.APIS.PUSH_WINDOW, {
              url: oauthUrl,
              target: "server",
              param: {
                title: {
                  title: "  ",
                  color: "#333333",
                  background: "#ffffff"
                }
              }
            });
          } else {
            Toast(result.msg);
          }
        })
        .catch(err => {

        });
    },

    //莫干山获取APP授权码
    getOAuthCode() {
      //请求bmserver获取授权码
      const serverUrl = "/serviceMarket/checkAuthToken.do";

      this.ajax({
        url: serverUrl,
        type: "get",
        controlLoading: true
      })
        .then(result => {
          if (String(result.success) == "true") {
            this.gotoOAuthCode();
          } else {
            const toAuthorizeUrl =
              config.bmwServiceUrl + "?" + APP.urlParam + "#/toAuthorize";
            AppUtil.call(AppUtil.APIS.PUSH_WINDOW, {
              url: toAuthorizeUrl,
              target: "server",
              param: {
                title: {
                  title: "去授权",
                  color: "#333333",
                  background: "#ffffff"
                }
              }
            });
          }
        })
        .catch(err => {

        });
    },

    bindNewOrderEvent() {
      const self = this;
      jsBridge.addNewOrderEventListener(() => {
        self.initTodayData(self.authMinusData);
      });
    },
    bindResumeEvent() {
      const self = this;
      jsBridge.addResumeEventListener(() => {
        self.initTodayData(self.authMinusData);
      });
    },
    bindBackEvent: function() {
      const self = this;
      jsBridge.addBackEventListener(function() {
        if (!self.backClickTimeId) {
          self.backClickTimeId = setTimeout(() => {
            self.backClickTime = 0;
            self.backClickTimeId = "";
          }, 3000);
        }
        self.backClickTime++;
        if (self.backClickTime === 1) {
          //Toast("再按一次退出程序");
          AppUtil.call(AppUtil.APIS.EXIT_APP, {});
        } else if (self.backClickTime === 2) {
          AppUtil.call(AppUtil.APIS.EXIT_APP, {});
        }
      });
    }
  },
  components: {
    customHeader,
    "v-loadmore": Loadmore
  },
  mounted() {
    this.urlParams = "?" + window.APP.urlParam;
    this.bindNewOrderEvent();
    this.bindResumeEvent();
    this.bindBackEvent();
    setTimeout(() => {
      this.initUser();
    }, 100);
  }
};
</script>

<style lang='scss' scoped>
@import "index";
</style>
